package com.fjb.controller.download;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fjb.controller.base.BaseController;

/**
 * @Description:下载
 * @author hemiao
 * @time:2020年1月4日 下午8:57:47
 */
@Controller
@RequestMapping("/download")
public class DownloadController extends BaseController{
	
	/**
	 * @Description:根据文件url下载文件
	 * void
	 * @exception:
	 * @author: hemiao
	 * @time:2019年5月29日 下午4:46:07
	 */
	@RequestMapping(value="/url")
	@ResponseBody
	public void downloadUrl(HttpServletRequest request,HttpServletResponse response) {
		String urlStr = request.getParameter("url");
	 	try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setConnectTimeout(10*1000);
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

			InputStream inputStream = conn.getInputStream();
			// 通知浏览器以附件形式下载		
			response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("lalalal测试.jpg", "UTF-8"));
			// 输出
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			//获取自己数组
			byte[] getData = readInputStream(inputStream);
			out.write(getData);
			if(out!=null){
				out.close();
			}
			if(inputStream!=null){
			    inputStream.close();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
	
}
